// packagesA/pages/updatemeaaage/index.js
const app = getApp()
import Dialog from '@vant/weapp/dialog/dialog';
const myRequest = require('../../../utils/request'); // 导入整个模块
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userinfo: {},
    usernameshow: false,
    gendershow: false,
    birthdayshow: false,
    signatureshow: false,
    gendercolumns: ['男', '女'],
    gender: '男',
    birthday: new Date().getTime(),
    maxDate: new Date().getTime(),
    minDate: new Date(1900, 1, 1).getTime(),
    username: '',
    password: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      userinfo: JSON.parse(wx.getStorageSync('userinfo')),
    })
  },


  //更换头像
  onChooseAvatar(e) {
    let self = this;
    const {
      avatarUrl
    } = e.detail

    console.log("获取到用户头像avatarUrl：" + avatarUrl)

    wx.uploadFile({
      url: app.globalData.baseAPI + '/api/updateimage',
      filePath: avatarUrl,
      name: 'file',
      header: {
        
        'authorization': wx.getStorageSync('token')
      },

      success(res) {
        const resurl = JSON.parse(res.data).data
        const userinfo = {
          ...self.data.userinfo,
          avatar: app.globalData.baseAPI + resurl
        }
        self.setData({
          userinfo: userinfo
        })
        app.globalData.userinfo = userinfo;
        wx.setStorageSync('userinfo', JSON.stringify(userinfo));
      },
      fail(res) {
        console.log('upload fail');
      }
    })

  },

  //显示用户名弹窗
  showusername() {
    if (this.data.userinfo.status == '2') {
      return Dialog.alert({
        message: '账号已绑定，无法更换！',
      }).then(() => {
        // on close
      });
    }
    this.setData({
      usernameshow: true
    })
  },
  // 关闭用户名弹窗
  closeusername() {
    this.setData({
      usernameshow: false,
      password: '',
      username: '',
    })
  },

  //用户名改变
  onusernameChange(event) {
    this.setData({
      username: event.detail
    })
  },
  //密码改变
  onpasswordChange(event) {
    this.setData({
      password: event.detail
    })
  },

  //确定账号绑定
  updateusername() {
    let that = this
    myRequest.post('/api/updateusername', {
      username: this.data.username,
      password: this.data.password,
    }).then(res => {
      wx.showToast({
        title: '绑定成功！',
        icon: 'success',
        duration: 1000
      })
      console.log(that.data);
      const userinfo = {
        ...that.data.userinfo,
        username: res.data,
        status: '2'
      }
      that.setData({
        userinfo: userinfo,
      })
      app.globalData.userinfo = userinfo;
      wx.setStorageSync('userinfo', JSON.stringify(userinfo));
    }).catch(err => {
      wx.showToast({
        title: '账号或密码错误！',
        icon: 'error',
        duration: 1000
      })
    })

  },


  //显示性别弹出框
  showgender() {
    this.setData({
      gendershow: true
    })
  },
  // 关闭性别弹窗
  closegender() {
    this.setData({
      gendershow: false
    })
  },

  // 选择性别改变
  onChangegender(event) {
    this.setData({
      gender: event.detail.value
    })
  },

  //确定性别改变
  updategender() {
    let that = this
    myRequest.post('/api/updatemessage', {
      gender: this.data.gender
    }).then(res => {
      wx.showToast({
        title: '更新成功！',
        icon: 'success',
        duration: 1000
      })
      const userinfo = {
        ...that.data.userinfo,
        gender: that.data.gender
      }
      that.setData({
        userinfo: userinfo,
        gendershow: false
      })
      app.globalData.userinfo = userinfo;
      wx.setStorageSync('userinfo', JSON.stringify(userinfo));

    }).catch(err => {
      wx.showToast({
        title: '更新失败！',
        icon: 'error',
        duration: 1000
      })
      that.setData({
        showgender: false
      })
    })
  
  },
  //显示生日弹出框
  showbirthday() {
    this.setData({
      birthdayshow: true
    })
  },
  // 关闭生日弹窗
  closebirthday() {
    this.setData({
      birthdayshow: false
    })
  },

  //生日改变
  onChangebirthday(event) {
    this.setData({
      birthday: event.detail
    })
  },

  getbirthday(givenTimestamp) {
    // 创建一个Date对象
    const date = new Date(givenTimestamp); // 将秒转换为毫秒

    // 格式化日期
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');

    // 组合成YYYY/MM/DD格式的字符串
    return `${year}/${month}/${day}`;

  },
  //确定生日改变
  updatebirthday() {
    let that = this
    myRequest.post('/api/updatemessage', {
      birthday: that.getbirthday(that.data.birthday)
    }).then(res=>{
      wx.showToast({
        title: '更新成功！',
        icon: 'success',
        duration: 1000
      })
      const userinfo = {
        ...that.data.userinfo,
        birthday: that.getbirthday(that.data.birthday)
      }
      that.setData({
        userinfo: userinfo,
        birthdayshow: false
      })
      app.globalData.userinfo = userinfo;
      wx.setStorageSync('userinfo', JSON.stringify(userinfo));
    }).catch(err=>{
      wx.showToast({
        title: '更新失败！',
        icon: 'error',
        duration: 1000
      })
      that.setData({
        showgender: false
      })
    })
   
  },
  //显示签名弹出框
  showsignature() {
    this.setData({
      signatureshow: true
    })
  },
  // 关闭签名弹窗
  closesignature() {
    this.setData({
      signatureshow: false
    })
  },
  // 输入框改变时
  onsignatureChange(event) {
    this.setData({
      signature: event.detail,
    })
  },
  //留言确定改变时
  updatesignature() {
    if (!this.data.signature) return this.setData({
      signatureshow: false
    })
    let that = this
    myRequest.post('/api/updatemessage', {
      signature: this.data.signature
    }).then(res => {
      wx.showToast({
        title: '更新成功！',
        icon: 'success',
        duration: 1000
      })
      const userinfo = {
        ...that.data.userinfo,
        signature: that.data.signature
      }
      console.log(userinfo);
      that.setData({
        userinfo: userinfo,
        signatureshow: false,
        signature: ''
      })
      app.globalData.userinfo = userinfo;
      wx.setStorageSync('userinfo', JSON.stringify(userinfo));
    }).catch(err => {
      wx.showToast({
        title: '更新失败！',
        icon: 'error',
        duration: 1000
      })
      that.setData({
        signatureshow: false,
        signature: ''
      })
    })
    
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})